package net.mayee.common;

import jodd.log.Logger;
import jodd.log.LoggerFactory;
import jodd.props.Props;
import net.mayee.alice.common.Definiens;
import net.mayee.alice.entity.coder.UploadCodeItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class Uploader {
    private static final Logger LOGGER = LoggerFactory.getLogger(Uploader.class);
    public static final String UPLOAD_TYPE_IMAGE = "IMAGE";
    public static final String UPLOAD_TYPE_FILE = "FILE";
    public static final String DEFAULT_CHARSET = "UTF-8";

    // 输出文件地址
    private String url = "";
    // 上传文件名
    private String fileName = "";
    // 状态
    private String state = "";
    // 文件类型
    private String type = "";
    // 原始文件名
    private String originalName = "";
    // 文件大小
    private long size = 0;
    private HttpServletRequest request = null;

    // 保存路径
    private String savePath = "";
    // 文件允许格式
    private String[] allowFiles = {".png", ".jpg", ".jpeg"};
    // 文件大小限制，单位KB
    private int maxSize = 10000;

    private Map<String, UploadCodeItem> errorInfo = new HashMap<String, UploadCodeItem>();
    private Map<String, String> paraMap = new HashMap<String, String>();

    public Uploader(HttpServletRequest request, String type) {
        this.request = request;
        errorInfo = CoderHelper.getInstance().getUploadCodeItemMap();
        Props props = AliceHelper.getInstance().getJoddProps();

        if (UPLOAD_TYPE_IMAGE.equals(type)) {
            savePath = props.getValue("upload.image.user.photo.savepath");
            try {
                maxSize = Integer.parseInt(props.getValue("upload.image.user.photo.max.size"));
            } catch (Exception e) {
                LOGGER.error(
                        AliceHelper.getInstance().getApplicationConfigErrorMessage("upload.image.user.photo.max.size", maxSize), e);
            }
            try {
                allowFiles = props.getValue("upload.image.user.photo.allowtypes").split(",");
            } catch (Exception e) {
                LOGGER.error(
                        AliceHelper.getInstance().getApplicationConfigErrorMessage("upload.image.user.photo.allowtypes", ".png|.jpg|.jpeg"), e);
            }
        } else if (UPLOAD_TYPE_FILE.equals(type)) {

        }
    }

    public String getParameter(String name) {
        return this.paraMap.get(name);
    }

    public void upload() throws Exception {
        boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
        if (!isMultipart) {
            this.state = this.errorInfo.get(Definiens.UC_ENTYPE).getText();
            return;
        }
        DiskFileItemFactory dff = new DiskFileItemFactory();
        String savePath = this.getFolder(this.savePath);
        dff.setRepository(new File(savePath));
        try {
            ServletFileUpload sfu = new ServletFileUpload(dff);
            sfu.setSizeMax(this.maxSize * 1024);
            sfu.setHeaderEncoding(DEFAULT_CHARSET);
            FileItemIterator fii = sfu.getItemIterator(this.request);
            while (fii.hasNext()) {
                FileItemStream fis = fii.next();
                if (!fis.isFormField()) {
                    this.originalName = fis.getName().substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
                    if (!this.checkFileType(this.originalName)) {
                        this.state = this.errorInfo.get(Definiens.UC_TYPE).getText();
                        continue;
                    }
                    this.fileName = this.getName(this.originalName);
                    this.type = this.getFileExt(this.fileName);
                    this.url = savePath + "/" + this.fileName;
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    File file = new File(this.getPhysicalPath(this.url));
                    FileOutputStream out = new FileOutputStream(file);
                    BufferedOutputStream output = new BufferedOutputStream(out);
                    Streams.copy(in, output, true);
                    this.state = this.errorInfo.get(Definiens.UC_SUCCESS).getDefText();
                    this.size = file.length();
                    break;
                } else {
                    String fname = fis.getFieldName();
                    BufferedInputStream in = new BufferedInputStream(fis.openStream());
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuffer result = new StringBuffer();
                    while (reader.ready()) {
                        result.append((char) reader.read());
                    }
                    this.paraMap.put(fname, new String(result.toString().getBytes(), DEFAULT_CHARSET));
                    reader.close();
                }
            }
        } catch (FileUploadBase.SizeLimitExceededException e) {
            this.state = this.errorInfo.get(Definiens.UC_SIZE).getText();
        } catch (FileUploadBase.InvalidContentTypeException e) {
            this.state = this.errorInfo.get(Definiens.UC_ENTYPE).getText();
        } catch (FileUploadException e) {
            this.state = this.errorInfo.get(Definiens.UC_REQUEST).getText();
        } catch (Exception e) {
            this.state = this.errorInfo.get(Definiens.UC_UNKNOWN).getText();
        }
    }

    /**
     * 获取文件扩展名
     *
     * @return string
     */
    private String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 依据原始文件名生成新文件名
     *
     * @return
     */
    private String getName(String fileName) {
        Random random = new Random();
        return this.fileName = "" + random.nextInt(10000)
                + System.currentTimeMillis() + this.getFileExt(fileName);
    }

    /**
     * 文件类型判断
     *
     * @param fileName
     * @return
     */
    private boolean checkFileType(String fileName) {
        Iterator<String> type = Arrays.asList(this.allowFiles).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据字符串创建本地目录 并按照日期建立子目录返回
     *
     * @param path
     * @return
     */
    private String getFolder(String path) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        path += "/" + formater.format(new Date());
        File dir = new File(this.getPhysicalPath(path));
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            } catch (Exception e) {
                this.state = this.errorInfo.get(Definiens.UC_DIR).getText();
                return "";
            }
        }
        return path;
    }

    /**
     * 根据传入的虚拟路径获取物理路径
     *
     * @param path
     * @return
     */
    private String getPhysicalPath(String path) {
        //String servletPath = this.request.getServletPath();
        String realPath = this.request.getSession().getServletContext()
                .getRealPath("/");
        //return new File(realPath).getParent() +"/" +path;
        return new File(realPath) + "/" + path;
    }

    public String getState() {
        return state;
    }

    public String getUrl() {
        return url;
    }

}
